<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


    <meta name="keywords" content="html5、css3、jquery">
    <meta name="description" content="一个前端工作者的学习笔记">
    <title>Html5 Canvas 实现图片合成 |</title>


    <style>
        img{ border:solid 1px #ddd;}
    </style></head>


<body>
<div align="center">
    <img src="./sun.png" width="300" height="300">
    <img src="./earth.png" width="300" height="300">
</div>
<div id="imgBox" align="center">
    <input type="button" value="一键合成" onclick="hecheng()">
</div>
<script>
    function hecheng(){
        draw(function(){
            document.getElementById('imgBox').innerHTML='<p style="padding:10px 0">合成图片成功！可以鼠标另存图片查看我是否是一张图片~~！</p><img src="'+base64[0]+'">';
        })
    }


    var data=['sun.png','earth.png','./img/timg.jpg'],base64=[];
    function draw(fn){
        var c=document.createElement('canvas'),
            ctx=c.getContext('2d'),
            len=data.length;
        c.width=400;
        c.height=400;
        ctx.rect(0,0,c.width,c.height);
        ctx.fillStyle='red';
        ctx.fill();
        function drawing(n){
            if(n<len){
                var img=new Image;
//img.crossOrigin = 'Anonymous'; //解决跨域

                img.src=data[n];
                img.onload=function(){
                    if(n==1){
                        ctx.drawImage(img,50,50,100,100);
                    }
                    else if(n==2){
                        ctx.drawImage(img,200,50,100,100);
                    }
                    else{
                        ctx.drawImage(img,0,0,c.width,c.height);
                    }
                    drawing(n+1);//递归
                }
            }else{
                       //保存生成作品图片
                base64.push(c.toDataURL("image/PNG",0.7));
                                     //alert(JSON.stringify(base64));
                fn();
                console.log(JSON.stringify(base64[0]))
            }
        }
        drawing(0);
    }
</script>
</body></html>